﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using DynamicComparer;
using Shuba.Model;

namespace Shuba.Web.admin
{
    public partial class user_list : basePage
    {
        bool IsView = false, IsAdd = false, IsEdit = false;
        const int rowsPerPage = 20;
        string currentPage;
        int jmlRow;

        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                this.Form.DefaultButton = btnSearch.UniqueID; 
                
                string acl = GetUserAccess("USER_LIST");
                IsView = IsUserView(acl);
                IsAdd = IsUserAdd(acl);
                IsEdit = IsUserEdit(acl);

                if (!IsView)
                {
                    string msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }

                LabelTitle.Text = GetPageTitle("USER_LIST");

                InitSort();
                ViewState["searchBy"] = "";
                currentPage = "1";

                BindData();

                if (IsAdd || IsEdit) gvList.Columns[6].Visible = true; 
                else gvList.Columns[6].Visible = false;
            }
        }

        private void BindData()
        {
            string AppCode = ConfigurationManager.AppSettings["app.code"];
            Shuba.Business.User _user = new Shuba.Business.User();

            if (ddlPaging.Items.Count == 0 || ViewState["searchBy"].ToString() != txtSearch.Text)
                currentPage = "1";
            else currentPage = ddlPaging.SelectedValue;

            jmlRow = _user.GetRowListPaging(txtSearch.Text, AppCode);

            List<UserInfo> list = _user.GetListPaging(txtSearch.Text, AppCode, int.Parse(currentPage), gvList.PageSize);
            ViewState["List"] = list;

            gvList.DataSource = list;
            gvList.DataBind();

            load_data_page();
        }

        protected void gvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvList.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected void gvList_OnSorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            gvList.PageIndex = 0;

            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                List<UserInfo> list = (List<UserInfo>)ViewState["List"];

                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<UserInfo> comparer = new DynamicComparer<UserInfo>(sort);
                list.Sort(comparer);

                gvList.DataSource = list;
                gvList.DataBind();
            }
        }

        protected void load_data_page()
        {
            int jmlHal = (int)Math.Ceiling((decimal)jmlRow / (decimal)rowsPerPage);
            string pageNum;

            footLink.Visible = (jmlHal > 0);

            ddlPaging.Items.Clear();
            for (int i = 0; i < jmlHal; i++)
            {
                pageNum = (i + 1).ToString();
                ddlPaging.Items.Add(new ListItem(pageNum, pageNum));
            }

            if (ViewState["searchBy"].ToString() == txtSearch.Text)
                ddlPaging.SelectedValue = currentPage;
            ViewState["searchBy"] = txtSearch.Text;

            lblPage.Text = "Page " + currentPage + " of " + jmlHal;

            firstLink.Visible = true;
            prevLink.Visible = true;
            nextLink.Visible = true;
            lastLink.Visible = true;

            if (ddlPaging.SelectedIndex <= 0)
            {
                firstLink.Visible = false;
                prevLink.Visible = false;
            }
            if (ddlPaging.SelectedIndex >= ddlPaging.Items.Count - 1)
            {
                nextLink.Visible = false;
                lastLink.Visible = false;
            }
        }

        protected void linkDataPage_Click(object sender, EventArgs e)
        {
            if (sender == firstLink)
                ddlPaging.SelectedIndex = 0;
            else if (sender == prevLink)
                ddlPaging.SelectedIndex--;
            else if (sender == nextLink)
                ddlPaging.SelectedIndex++;
            else if (sender == lastLink)
                ddlPaging.SelectedIndex = ddlPaging.Items.Count - 1;
            BindData();
        }

        protected void ddlPaging_IndexChange(object sender, EventArgs e)
        {
            BindData();
        }

        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Reset")
            {
                string ParamID = e.CommandArgument.ToString();

                Shuba.Business.User user = new Shuba.Business.User();
                Shuba.Model.UserInfo info = user.GetByID(Convert.ToInt32(ParamID), ConfigurationManager.AppSettings["app.code"]);
                info.IsLogin = false;

                AddLog("UPDATE", "RESET LOGIN STATUS OF [" + info.Nip + " - " + info.Name + "]");

                user.Update(info);
                
                Alert("Login Status Successfully Reset");

                BindData();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected void btnExcel_Click(object sender, EventArgs e)
        {
            gvList.AllowPaging = false;
            BindData();
            GridViewExportUtil.Export("user_" + ConfigurationManager.AppSettings["app.code"] + "_" + ProcessingDate().ToString("ddMMMyyyy") + ".xls", gvList);

            //Response.Clear();
            //Response.AddHeader("content-disposition", "attachment;filename=log" + ProcessingDate().ToString("ddMMMyyyy") + ".xls");
            //Response.Charset = "";

            //// If you want the option to open the Excel file without saving than
            //// comment out the line below
            //// Response.Cache.SetCacheability(HttpCacheability.NoCache);

            //Response.ContentType = "application/vnd.xls";
            //System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            //System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            //gvList.RenderControl(htmlWrite);

            //Response.Write(stringWrite.ToString());
            //Response.End();        
        }
    }
}